package cn.bonoon.kernel.web;

import java.util.List;

import cn.bonoon.kernel.menus.ItemInfo;
import cn.bonoon.kernel.support.IOperator;
import cn.bonoon.kernel.support.services.UserService;
import cn.bonoon.kernel.web.models.StandardModel;

public class StandardKeyChecker implements KeyChecker{
	/**
	 * 在菜单文件里定义的本功能的操作权限
	 */
	private final long defineActions;
	/**
	 * 当前操作用户的权限定义
	 */
	private final long privilegeActions;
	
	public StandardKeyChecker(long defineActions, List<Long> actions){
		this.defineActions = defineActions;
		long privilegeActions = 0; 
		if(null != actions){
			for (Long action : actions) {
				privilegeActions = privilegeActions | action;
			}
		}
		this.privilegeActions = privilegeActions;
	}
	
	@Override
	public boolean check(int key){
		//没有定义权限
		int val = 1 << key;
		if((defineActions & val) == 0)return true;
		return (privilegeActions & val) == val;
	}
	
	public static void setChecker(StandardModel model, ItemInfo item, IOperator user, UserService userService){
		if (null == item){
			// 没有在菜单文件里定义过.直接返回,不需要生成框架
			throw new RuntimeException("没有定义菜单！");
		}
		int defActions = item.getActionPrivileges();
		if(defActions > 0){
			//通过当前的key来控制权限
			List<Long> actions = userService.getActions(item, user);
			//需要添加一个keyChecker来处理操作的权限
			model.addObject(CHECKER_PROPERTY_NAME, new StandardKeyChecker(defActions, actions));
		}else{
			//所有权限
			model.addObject(CHECKER_PROPERTY_NAME, EMPTY);
		}
	}
}
